package com.huawei.codearts.tools.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtils {

    private final static JedisPool jedisPool;
    private final static String HOST = SettingUtils.getProperty("redis.host");
    private final static int PORT = Integer.parseInt(SettingUtils.getProperty("redis.port"));
    private final static int TIMEOUT = Integer.parseInt(SettingUtils.getProperty("redis.timeout"));
    private final static String AUTH = SettingUtils.getProperty("redis.auth");
    private final static int SELECT = Integer.parseInt(SettingUtils.getProperty("redis.select"));
    private final static int MAX_TOTAL = Integer.parseInt(SettingUtils.getProperty("redis.jedis.pool.max-active"));  // 最大连接数
    private final static int MAX_IDLE = Integer.parseInt(SettingUtils.getProperty("redis.jedis.pool.max-idle"));  // 连接池中的最大空闲连接
    private final static int MIN_IDLE = Integer.parseInt(SettingUtils.getProperty("redis.jedis.pool.min-idle"));  // 连接池中的最小空闲连接
    private final static int MAX_WAIT = Integer.parseInt(SettingUtils.getProperty("redis.jedis.pool.max-wait"));  // 连接池最大阻塞等待时间 ms

    static {
        //配置连接池
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //最大连接
        jedisPoolConfig.setMaxTotal(MAX_TOTAL);
        //最大空闲连接
        jedisPoolConfig.setMaxIdle(MAX_IDLE);
        //最小空闲连接
        jedisPoolConfig.setMinIdle(MIN_IDLE);
        //最长等待时间,ms
        jedisPoolConfig.setMaxWaitMillis(MAX_WAIT);
        if (AUTH == null || AUTH.isEmpty()) {
            jedisPool = new JedisPool(jedisPoolConfig, HOST, PORT, TIMEOUT);
        } else {
            jedisPool = new JedisPool(jedisPoolConfig, HOST, PORT, TIMEOUT, AUTH, SELECT);
        }
    }

    //获取jedis对象
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }
}
